import React, { useRef, useState } from 'react';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import {
  Button,
  Space,
  Popconfirm,
  message,
  Tag,
  Switch,
  Tooltip,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ApiOutlined,
  RobotOutlined,
  BulbOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { LlmModel } from '../../types';
import { llmModelService } from '../../services/llmModels';
import { useTranslation } from 'react-i18next';

const LlmModelList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const { t } = useTranslation();

  const fetchModels = async (params: any) => {
    try {
      const data = await llmModelService.getLlmModels();
      return {
        data: data,
        success: true,
        total: data.length,
      };
    } catch (error) {
      message.error(t('llmModels.loadError'));
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  const handleDelete = async (id: number) => {
    setLoading(true);
    try {
      await llmModelService.deleteLlmModel(id);
      message.success(t('llmModels.deleteSuccess'));
      actionRef.current?.reload();
    } catch (error) {
      message.error(t('llmModels.deleteError'));
    } finally {
      setLoading(false);
    }
  };

  const handleToggle = async (id: number) => {
    try {
      await llmModelService.toggleLlmModel(id);
      message.success(t('llmModels.toggleSuccess'));
      actionRef.current?.reload();
    } catch (error) {
      message.error(t('llmModels.toggleError'));
    }
  };

  const getCategoryIcon = (category: string) => {
    return category === 'Chat' ? <RobotOutlined /> : <BulbOutlined />;
  };

  const getCategoryColor = (category: string) => {
    return category === 'Chat' ? 'blue' : 'purple';
  };

  const columns: ProColumns<LlmModel>[] = [
    {
      title: t('llmModels.modelId'),
      dataIndex: 'modelId',
      width: 200,
      render: (_, record: LlmModel) => <code>{record.modelId}</code>,
      copyable: true,
    },
    {
      title: t('llmModels.name'),
      dataIndex: 'name',
      render: (_, record: LlmModel) => (
        <Space>
          <ApiOutlined />
          <strong>{record.name}</strong>
          <Tag color={getCategoryColor(record.category)} icon={getCategoryIcon(record.category)}>
            {record.category}
          </Tag>
        </Space>
      ),
    },
    {
      title: t('llmModels.provider'),
      dataIndex: 'provider',
    },
    {
      title: t('llmModels.endpoint'),
      dataIndex: 'endpoint',
      ellipsis: true,
      search: false,
      render: (_, record: LlmModel) => (
        <Tooltip title={record.endpoint}>
          <span>{record.endpoint}</span>
        </Tooltip>
      ),
    },
    {
      title: t('llmModels.description'),
      dataIndex: 'description',
      ellipsis: true,
      search: false,
      render: (_, record: LlmModel) => record.description || '-',
    },
    {
      title: t('llmModels.status'),
      dataIndex: 'isEnabled',
      search: false,
      render: (_, record: LlmModel) => (
        <Switch
          checked={record.isEnabled}
          onChange={() => handleToggle(record.id)}
          checkedChildren={t('common.enabled')}
          unCheckedChildren={t('common.disabled')}
        />
      ),
    },
    {
      title: t('llmModels.createdBy'),
      dataIndex: 'createdBy',
      search: false,
      render: (_, record: LlmModel) => record.createdBy.username,
    },
    {
      title: t('llmModels.createdAt'),
      dataIndex: 'createdAt',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: t('common.actions'),
      valueType: 'option',
      width: 200,
      render: (_, record: LlmModel) => [
        <Button
          key="edit"
          type="link"
          icon={<EditOutlined />}
          onClick={() => navigate(`/llm-models/edit/${record.id}`)}
        >
          {t('common.edit')}
        </Button>,
        <Popconfirm
          key="delete"
          title={t('llmModels.deleteConfirm')}
          onConfirm={() => handleDelete(record.id)}
          okText={t('common.yes')}
          cancelText={t('common.no')}
        >
          <Button type="link" danger icon={<DeleteOutlined />} loading={loading}>
            {t('common.delete')}
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <ProTable<LlmModel>
      columns={columns}
      actionRef={actionRef}
      request={fetchModels}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      pagination={{
        defaultPageSize: 10,
        showSizeChanger: true,
      }}
      dateFormatter="string"
      headerTitle={t('llmModels.title')}
      toolBarRender={() => [
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={() => navigate('/llm-models/create')}
          type="primary"
        >
          {t('llmModels.createModel')}
        </Button>,
      ]}
    />
  );
};

export default LlmModelList;
